import json
import asyncio

HOST = '0.0.0.0'
PORT = 40001
def check_win(zb, single_list):
    if len(single_list) < 5:
        return False
    # 获取最后一次下子的坐标
    x, y = zb

    # 检查水平方向
    count = 0
    for piece in single_list:
        if piece[0] == x and abs(piece[1] - y) < 5:
            count += 1
    if count >= 5:
        return True

    # 检查垂直方向
    count = 0
    for piece in single_list:
        if piece[1] == y and abs(piece[0] - x) < 5:
            count += 1
    if count >= 5:
        return True

    # 检查主对角线方向（右上到左下）
    count = 0
    for piece in single_list:
        if abs(piece[0] - x) == abs(piece[1] - y) and abs(piece[0] - x) < 5:
            count += 1
    if count >= 5:
        return True

    # 检查副对角线方向（左上到右下）
    count = 0
    for piece in single_list:
        if abs(piece[0] - x) == abs(piece[1] - y) and abs(piece[0] - x) < 5:
            count += 1
    if count >= 5:
        return True

    return False
# 存储所有客户端连接
ss_clients = []
list_black = []
list_white = []

async def handle_client(reader, writer):
    addr = writer.get_extra_info('peername')
    print("Client connected:", addr)
    ss_clients.append(writer)

    while True:
        data = await reader.read(1024)
        if not data:
            print("Client disconnected:", addr)
            ss_clients.remove(writer)
            continue
        message = json.loads(data)
        print(message)
        color = message['color']
        zb = message['zb']
        if color=='black':
            if zb in list_black:
                continue

            list_black.append(zb)

            win = check_win(zb, list_black)
            print(win)
            print(list_black)
            if win:
                print(" black win")
                msg_result = {
                    "type": 0,
                    "winner": "black",
                    "zb":zb
                }
                for client_writer in ss_clients:
                    # 给所有人发
                    client_writer.write(json.dumps(msg_result).encode())
                    await client_writer.drain()
                continue
        else:
            if zb in list_white:
                continue
            list_white.append(zb)
            win = check_win(zb, list_white)
            if win:
                print(" white win")
                msg_result = {
                    "type": 0,
                    "winner": "white",
                    "zb": zb
                }
                for client_writer in ss_clients:
                    # 给所有人发
                    client_writer.write(json.dumps(msg_result).encode())
                    await client_writer.drain()
                continue
        for client_writer in ss_clients:
            # 给所有人发
            client_writer.write(data)
            await client_writer.drain()


async def main():
    server = await asyncio.start_server(
        handle_client, HOST, PORT)

    addr = server.sockets[0].getsockname()
    print(f'Serving on {addr}')

    async with server:
        await server.serve_forever()


asyncio.run(main())
